package com.android.xunxian.activity;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.xunxian.entry.GuanW;
import com.android.xunxian.entry.JWdu;
import com.android.xunxian.utils.Util;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.Polyline;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.model.LatLng;
import com.oa.android.MyApplication;
import com.oa.android.R;

import org.json.JSONArray;
import org.json.JSONException;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by 邹啟华 on 2016/7/20.
 */
public class MapActivity extends Activity implements View.OnClickListener {

    private MapView mapView;
    private ImageView close;
    private TextView title;
    BaiduMap mBaiduMap;
    BitmapDescriptor mRedTexture = BitmapDescriptorFactory.fromAsset("icon_road_red_arrow.png");
    BitmapDescriptor mBlueTexture = BitmapDescriptorFactory.fromAsset("icon_road_blue_arrow.png");
    // 纹理折线，点击时获取折线上点数及width
    Polyline mTexturePolyline;
    private String id;
    private List<JWdu> jWduList;
    private List<JWdu> jxlist;
    private Double la=0.0d;
    private Double lo=0.0d;
    private String jx;
    private String selcet;//是否选中，本地保存
    private Util util;
    private String[] array;
    private List<GuanW> guanwTypeList;

    private List<List<JWdu>> gwList;
    // 普通折线，点击时改变宽度
    Polyline mPolyline;
    private String xunId;

    private LocationClientOption.LocationMode tempMode = LocationClientOption.LocationMode.Hight_Accuracy;
    private String tempcoor = "bd09ll";
    public LocationClient mLocationClient = null;
    public MyLocationListenner myListener = new MyLocationListenner();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.map_activity);
        close = (ImageView) findViewById(R.id.close);
        title = (TextView) findViewById(R.id.title_text);
        mapView = (MapView) findViewById(R.id.mapView);
        jx = getIntent().getStringExtra("jx");
        xunId= getIntent().getStringExtra("xunId");
        // 开启定位图层
//        mBaiduMap.setMyLocationEnabled(true);
        title.setText("轨迹查看");
        close.setOnClickListener(this);
        util = new Util(this);
        selcet = util.getUser("guanw");
        System.out.println("selcet---" + selcet);
        if (Util.NoNull(selcet)) {
            guanwTypeList=new ArrayList<>();
            gwList=new ArrayList<>();
            if (selcet.contains(",")) {
                array = selcet.split(",");
            } else {
                array = new String[1];
                array[0] = selcet;
            }

        }
        if (Util.NoNull(jx)) {
            jxlist = new ArrayList<>();
            getYroute();
        }

        mBaiduMap = mapView.getMap();
        try {
//            la=27.107361;
//            lo=107.476103;
            String a = getIntent().getStringExtra("la");
            String b = getIntent().getStringExtra("lo");
            Log.i("la---------", a+"");
            Log.i("lo---------", b+"");
            if (!Util.NoNull(a) || !Util.NoNull(b)) {
                if (jxlist!=null&&jxlist.size()>0){
                    la = Double.parseDouble(jxlist.get(0).getLatitude());
                    lo = Double.parseDouble(jxlist.get(0).getLongitude());
                }

            } else {
                la = Double.parseDouble(a);
                lo = Double.parseDouble(b);
            }

            if(la<=0||lo<=0){
                mLocationClient = new LocationClient(this);
                mLocationClient.registerLocationListener(myListener);
                setLocationOption();
                mLocationClient.start();// 启动定位
            }else{
                LatLng p111 = new LatLng(la, lo);
                MapStatus.Builder builder = new MapStatus.Builder();
                builder.target(p111).zoom(14.0f);
                mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
            }
//            la=Double.parseDouble();
//            lo=Double.parseDouble();


            jWduList = MyApplication.dbManager.selector(JWdu.class).where("xunId","=",xunId).findAll();
            if (array!=null){

            for (int i=0;i<array.length;i++){
                List<GuanW> list= MyApplication.dbManager.selector(GuanW.class).where("LINEKIND","=",array[i]).findAll();
                if (list!=null&&list.size()>0){
                    guanwTypeList.addAll(list);
                }
            }
                System.out.println("guanwTypeList.size()---"+guanwTypeList.size());

            }
            getGwAll();
            setMap();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void getYroute() {
        try {
            if (Util.NoNull(jx)){


            JSONArray jsonArray = new JSONArray(jx);
            if (jsonArray.length() > 0) {
                for (int i = 0; i < jsonArray.length(); i++) {
                    Log.i("==============", jsonArray.getJSONArray(i).getString(0));
                    Log.i("-----------------", jsonArray.getJSONArray(i).getString(1));
                    JWdu jWdu = new JWdu();
                    jWdu.setLatitude(jsonArray.getJSONArray(i).getString(1));
                    jWdu.setLongitude(jsonArray.getJSONArray(i).getString(0));
                    jxlist.add(jWdu);
                }
            }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void getGwAll(){
        if (guanwTypeList!=null&&guanwTypeList.size()>0){
            for (int a=0;a<guanwTypeList.size();a++){
                List<JWdu> jWdus=new ArrayList<>();
                try {
                    if(Util.NoNull(guanwTypeList.get(a).getXYS())){

                    JSONArray jsonArray = new JSONArray(guanwTypeList.get(a).getXYS());
                    if (jsonArray.length() > 0) {
                        for (int i = 0; i < jsonArray.length(); i++) {
                            Log.i("qqqqqqqqq", jsonArray.getJSONArray(i).getString(0));
                            Log.i("bbbbbbbbbbbb", jsonArray.getJSONArray(i).getString(1));
                            JWdu jWdu = new JWdu();
                            jWdu.setLatitude(jsonArray.getJSONArray(i).getString(1));
                            jWdu.setLongitude(jsonArray.getJSONArray(i).getString(0));
                            jWdus.add(jWdu);
                        }
                        gwList.add(jWdus);

                    }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * Called when a view has been clicked.
     *
     * @param v The view that was clicked.
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.close:
                finish();
                break;
        }
    }


    private void setMap() {
        List<LatLng> points11 = new ArrayList<LatLng>();
        // 添加多纹理分段的折线绘制
        if (jWduList != null && jWduList.size() > 1) {
            for (int i = 0; i < jWduList.size(); i++) {
                LatLng p111 = new LatLng(Double.parseDouble(jWduList.get(i).getLatitude()), Double.parseDouble(jWduList.get(i).getLongitude()));
                points11.add(p111);
            }

            List<BitmapDescriptor> textureList = new ArrayList<BitmapDescriptor>();
            textureList.add(mRedTexture);
            List<Integer> textureIndexs = new ArrayList<Integer>();
            textureIndexs.add(0);
            OverlayOptions ooPolyline11 = new PolylineOptions().width(10)
                    .points(points11).dottedLine(true).customTextureList(textureList).textureIndex(textureIndexs);
            mTexturePolyline = (Polyline) mBaiduMap.addOverlay(ooPolyline11);
        }
        List<LatLng> points2 = new ArrayList<LatLng>();
        if (jxlist != null && jxlist.size() > 1) {
            for (int j = 0; j < jxlist.size(); j++) {
                LatLng p = new LatLng(Double.parseDouble(jxlist.get(j).getLatitude()), Double.parseDouble(jxlist.get(j).getLongitude()));
                points2.add(p);
            }
            List<BitmapDescriptor> textureList1 = new ArrayList<BitmapDescriptor>();
            textureList1.add(mBlueTexture);
            List<Integer> textureIndexs1 = new ArrayList<Integer>();
            textureIndexs1.add(0);
            OverlayOptions ooPolyline2 = new PolylineOptions().width(10)
                    .points(points2).dottedLine(true).customTextureList(textureList1).textureIndex(textureIndexs1);
            mTexturePolyline = (Polyline) mBaiduMap.addOverlay(ooPolyline2);

        }

        if (gwList!=null&&gwList.size()>0){
            for (int k=0;k<gwList.size();k++){
                List<LatLng> points = new ArrayList<LatLng>();
                for (int g=0;g<gwList.get(k).size();g++){
                    LatLng p = new LatLng(Double.parseDouble(gwList.get(k).get(g).getLatitude()), Double.parseDouble(gwList.get(k).get(g).getLongitude()));
                    points.add(p);
                }

                OverlayOptions ooPolyline = new PolylineOptions().width(10)
                        .color(Color.parseColor(guanwTypeList.get(k).getLINECOLOR())).points(points);
                mPolyline = (Polyline) mBaiduMap.addOverlay(ooPolyline);


            }
        }



        mapView.refreshDrawableState();


    }


    @Override
    protected void onPause() {
        mapView.onPause();
        super.onPause();
    }

    @Override
    protected void onResume() {
        mapView.onResume();
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        mapView.onDestroy();
        mRedTexture.recycle();
        super.onDestroy();
    }


    // //////////////////////////定位\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
    private void setLocationOption() {
        LocationClientOption option = new LocationClientOption();
        // TODO Auto-generated method stub
        option.setLocationMode(tempMode);// 可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType(tempcoor);// 可选，默认gcj02，设置返回的定位结果坐标系，
        int span = 1000;
        System.out.println("span==="+span);
        option.setScanSpan(span);// 可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        option.setIsNeedAddress(false);// 可选，设置是否需要地址信息，默认不需要
        option.setOpenGps(true);// 可选，默认false,设置是否使用gps
        option.setLocationNotify(false);// 可选，默认false，设置是否当gps有效时按照1S1次频率输出GPS结果
        option.setIgnoreKillProcess(true);// 可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
        option.setEnableSimulateGps(false);// 可选，默认false，设置是否需要过滤gps仿真结果，默认需要
        option.setIsNeedLocationDescribe(true);// 可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        option.setIsNeedLocationPoiList(false);// 可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        mLocationClient.setLocOption(option);

    }

    public class MyLocationListenner implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation arg0) {
            // TODO Auto-generated method stub
            if (arg0 != null) {

                LatLng p111 = new LatLng(arg0.getLatitude(), arg0.getLongitude());
                MapStatus.Builder builder = new MapStatus.Builder();
                builder.target(p111).zoom(14.0f);
                mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
                // handler.sendEmptyMessage(1);
                mLocationClient.stop();



            }
        }

    }
}
